import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/userStore'
import Login from '@/views/Login.vue'
import Home from '@/views/Home/index.vue'
import Welcome from '@/views/Home/Welcome.vue'
const Users = () => import('@/views/Users/index.vue')
const Roles = () => import('@/views/Authority/Roles.vue')
const Rights = () => import('@/views/Authority/Rights.vue')
const Categories = () => import('@/views/Product/Categories.vue')
const Goods = () => import('@/views/Product/Goods.vue')
const Params = () => import('@/views/Product/Params.vue')
const Add = () => import('@/views/Product/Add.vue')
const Orders = () => import('@/views/Order/index.vue')
const Reports = () => import('@/views/Reports/index.vue')

const router = createRouter({
    history: createWebHistory(import.meta.env.BASE_URL),
    routes: [
        { path: '/', redirect: '/login' },
        { path: '/login', component: Login },
        {
            path: '/home',
            component: Home,
            redirect: '/home/welcome',
            children: [
                { path: 'welcome', component: Welcome },
                { path: 'users', component: Users },
                { path: 'roles', component: Roles },
                { path: 'rights', component: Rights },
                { path: 'goods', component: Goods },
                { path: 'goods/add', component: Add },
                { path: 'params', component: Params },
                { path: 'categories', component: Categories },
                { path: 'orders', component: Orders },
                { path: 'reports', component: Reports }
            ]
        }
    ]
})


router.beforeEach((to, from, next) => {
    if (to.path === '/login') return next()

    const userStore = useUserStore()
    const { token } = userStore.userInfo
    if (token) {
        next()
    } else {
        next('/login')
    }
})

export default router